package com.shujia.advance;

import com.shujia.utils.BaseUtils;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/*
    模拟先查询索引表再查询源数据表的过程
    student_index 行键是姓名，找到列值学号
    students2     拿到学号去源数据表找班级

    1500100068,宣南蓉,23,女,理科一班
 */
public class HBaseIndexDemo {
    private static Connection conn;
    private static Admin admin;

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入要查询的学生姓名：");
        String name = sc.next();

        init();

        //通过索引查询源数据表得到某个学生的班级
        String clazz = getClazzByName(name);
        System.out.println(name + "学生所在的班级为：" + clazz);
    }

    public static String getClazzByName(String name) throws Exception {
        //先查询索引表student_index
        //获取索引表
        Table studentIndex = conn.getTable(TableName.valueOf("student_index"));
        Get get = new Get(Bytes.toBytes(name));
        get.addFamily(Bytes.toBytes("info"));
        Result result = studentIndex.get(get); //获取一行数据，我们的目的就是获取列名
        //在不知道列名的情况下，只能使用listCells获取一行中的所有列
        List<Cell> cells = result.listCells();
        //我们知道这个表只有一列数据，所以cells只有一个单元格数据
        Cell cell = cells.get(0);
        //获取列名
        String id = Bytes.toString(CellUtil.cloneQualifier(cell));

        //根据学号去原表查询班级
        Table students2 = conn.getTable(TableName.valueOf("students_1"));
        Get get2 = new Get(Bytes.toBytes(id));
        get2.addColumn(Bytes.toBytes("info"), Bytes.toBytes("clazz"));
        Result result1 = students2.get(get2);
        return Bytes.toString(result1.getValue(Bytes.toBytes("info"), Bytes.toBytes("clazz")));
    }

    public static void init() throws IOException {
        //获取数据库的连接对象和数据库的操作对象
         conn = BaseUtils.getConnection();
         admin = conn.getAdmin();
    }
}
